package kr.or.eclipse.cedt;

import java.io.InputStream;

import org.eclipse.core.resources.IStorage;
import org.eclipse.core.runtime.Assert;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.ui.IEditorInput;
import org.eclipse.ui.IEditorPart;
import org.eclipse.ui.IStorageEditorInput;
import org.eclipse.ui.PartInitException;
import org.eclipse.ui.forms.editor.SharedHeaderFormEditor;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONTokener;

public class ManifestEditor extends SharedHeaderFormEditor {

	private JSONObject model;

	public ManifestEditor() {
	}

	@Override
	protected void addPages() {
		try {
			addPage(new TestPage(this, "basic", "Basic"));
		} catch (PartInitException e) {
			e.printStackTrace();
		}
	}

	@Override
	public void doSave(IProgressMonitor monitor) {

	}

	@Override
	public void doSaveAs() {

	}

	@Override
	public boolean isSaveAsAllowed() {
		return false;
	}

	@Override
	protected void createPages() {
		super.createPages();

		load(getEditorInput());
	}

	private void load(IEditorInput input) {
		Assert.isLegal(input instanceof IStorageEditorInput, "CEDT supports only IStorageEditorInput!");
		IStorageEditorInput storageEditorInput = (IStorageEditorInput) input;
		try {
			IStorage storage = storageEditorInput.getStorage();
			InputStream contents = storage.getContents();

			JSONTokener tokener = new JSONTokener(contents);
			JSONObject model = new JSONObject(tokener);
			setModel(model);
		} catch (CoreException e) {
			e.printStackTrace();
		} catch (JSONException e) {
			e.printStackTrace();
		}
	}

	private void setModel(JSONObject model) {
		if (this.model == model) {
			return;
		}
		this.model = model;
	}
}
